import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
import QtMultimedia 5.12
import QtQml 2.0

//底部工具栏
Rectangle
{
    property var playList: []
    property int current: -1
    property int sliderTo: 100
    property int sliderFrom: 0
    property int sliderValue: 0

    property var playModeList: [{icon:"single-repeat",name:"单曲循环"},
        {icon:"repeat",name:"顺序播放"},{icon:"random",name:"随机播放"}]
    property int currentPlayMode: 0
    property bool playbackChangeCallbackEnabled: false
    property string musicCover: "qrc:/images/player"

    property string musicName: ""
    property string musicArtist: ""

    property int playingState: 0

    Layout.fillWidth: true
    height: 60
    color: "#1500AAAA"

    MouseArea
    {
        anchors.fill: parent
        onPressed: layoutHeaderView.setPoint(mouseX, mouseY)
        onMouseXChanged:layoutHeaderView.moveX(mouseX)
        onMouseYChanged:layoutHeaderView.moveY(mouseY)
    }
    RowLayout
    {
        anchors.fill:parent

        Item
        {
            Layout.preferredWidth: parent.width/10
            Layout.fillHeight: true
            Layout.fillWidth: true

            MouseArea
            {
                anchors.fill: parent
                onPressed: layoutHeaderView.setPoint(mouseX, mouseY)
                onMouseXChanged:layoutHeaderView.moveX(mouseX)
                onMouseYChanged:layoutHeaderView.moveY(mouseY)
            }
        }
        MusicIconButton
        {
            //Layout.preferredWidth: 50
            iconWidth: 32
            iconHeight: 32
            iconSource: "qrc:/images/previous"
            toolTip: "上一曲"
            onClicked:
            {
                playPrevious()
            }
        }
        MusicIconButton
        {
            //Layout.preferredWidth: 50
            iconSource: playingState ===0?"qrc:/images/stop":"qrc:/images/pause"
            iconWidth:  32
            iconHeight: 32
            toolTip: "暂停/播放"
            onClicked:
            {
                playOrPause()
            }
        }
        MusicIconButton
        {
            //Layout.preferredWidth: 50
            iconWidth: 32
            iconHeight: 32
            iconSource: "qrc:/images/next"
            toolTip: "下一曲"

            onClicked:
            {
                playNext("")
            }
        }
        Item
        {
            Layout.preferredWidth: parent.width/2
            Layout.fillHeight: true
            Layout.fillWidth: true
            Layout.topMargin: 25
            visible: !layoutHeaderView.isSmallWindow
            Text
            {
                anchors.left: slider.left
                anchors.bottom: slider.top
                anchors.leftMargin: 5
                text: musicName+"-"+musicArtist
                font.family: window.m_FONT_FAMLIY
                color: "#ffffff"
            }
            Text
            {
                id:timeText
                text: qsTr("00:00/05:30")
                anchors.right: slider.right
                anchors.bottom: slider.top
                anchors.rightMargin: 5
                font.family: window.m_FONT_FAMLIY
                color: "#ffffff"
            }
            Slider
            {
                id:slider
                width: parent.width
                Layout.fillWidth: true
                height: 25
                to: sliderTo
                from: sliderFrom
                value: sliderValue
                visible: !layoutHeaderView.isSmallWindow

                onMoved:
                {
                    if(mediaplayer.playbackState == MediaPlayer.playbackState)
                    {

                    }

                    mediaplayer.seek(value)
                }


                background: Rectangle
                {
                    width:slider.availableWidth
                    height:4
                    radius:2
                    color:"#e9f4ff"
                    x:slider.leftPadding
                    y:slider.topPadding+(slider.availableHeight-height)/2

                    Rectangle
                    {
                        width: slider.visualPosition*parent.width
                        height:parent.height
                        color: "#808cecf3"
                        radius: 2
                    }
                }
                handle: Rectangle
                {
                    color:"#f0f0f0"
                    border.color:"#73a7ab"
                    border.width:0.5
                    width:15
                    height:15
                    radius:5
                    x:slider.leftPadding + (slider.availableWidth - width)*slider.visualPosition
                    y:slider.topPadding + (slider.availableHeight - height)/2
                }
            }

        }

        MusicBorderImage
        {
            width: 50
            height: 45
            imgSrc: musicCover
            MouseArea
            {
                anchors.fill: parent
                cursorShape: Qt.PointingHandCursor
                onPressed:
                {
                    musicCover.scale=0.9
                    pageDetailView.visible = !pageDetailView.visible
                    pageHomeView.visible = !pageHomeView.visible
                    appBackground.showDefaultBackground = !appBackground.showDefaultBackground
                }
                onReleased:
                {
                    musicCover.scale=1.0
                }
            }
        }

        MusicIconButton
        {
            Layout.preferredWidth: 50
            iconWidth: 32
            iconHeight: 32
            iconSource: "qrc:/images/favorite"
            toolTip: "我喜欢"
            onClicked: saveFavorite(playList[current])
        }
        MusicIconButton
        {
            id:playMode
            Layout.preferredWidth: 50
            iconWidth: 32
            iconHeight: 32
            iconSource: "qrc:/images/"+playModeList[currentPlayMode].icon
            toolTip: playModeList[currentPlayMode].name
            onClicked:
            {
                changePlayMode()
            }
        }
        Item
        {
            Layout.preferredWidth: parent.width/10
            Layout.fillHeight: true
            Layout.fillWidth: true

            MouseArea
            {
                anchors.fill: parent
                onPressed: layoutHeaderView.setPoint(mouseX, mouseY)
                onMouseXChanged:layoutHeaderView.moveX(mouseX)
                onMouseYChanged:layoutHeaderView.moveY(mouseY)
            }
        }
    }
    Component.onCompleted:
    {
        currentPlayMode = settings.value("currentPlayMode", 0)
    }

    onCurrentChanged:
    {
        playbackChangeCallbackEnabled=false
        playMusic(current)
    }

    function saveFavorite(value={})
    {
        if(!value||!value.id) return
        var favorite = favoriteSettings.value("favorite",[])
        var i = favorite.findIndex(item=>value.id === item.id)

        if(i>=0)
        {
            favorite.splice(i,1)
        }

        favorite.unshift({
                             id:value.id+"",
                             name:value.name,
                             artist:value.artist,
                             url:value.url?value.url:"",
                             type:value.type?value.type:"",
                             album:value.album?value.album:"本地音乐",
                             cover:""

                         })
        if(favorite.length>500)
        {
            favorite.pop()
        }

        favoriteSettings.setValue("favorite", favorite)
    }

    function saveHistory(index = 0)
    {
        if(playList.length<index+1) return
        var item = playList[index]
        if(!item||!item.id) return
        var history = historySettings.value("history",[])
        var i = history.findIndex(value=>value.id === item.id)

        if(i>=0)
        {
            history.splice(i,1)
        }

        history.unshift({
                            id:item.id+"",
                            name:item.name,
                            artist:item.artist,
                            url:item.url?item.url:"",
                            type:item.type?item.type:"",
                            album:item.album?item.album:"本地音乐",
                            cover:""

                        })
        if(history.length>100)
        {
            history.pop()
        }

        historySettings.setValue("history", history)
    }

    function playPrevious()
    {
        if(playList.length<1) return
        switch(currentPlayMode)
        {
        case 0:
        case 1:
            current = (current-1+playList.length)%playList.length
            break
        case 2:
        {
            var random = parseInt(Math.random()*playList.length)
            current = random===current?random+1:random

        }
        }
    }

    function playOrPause()
    {
        if(!mediaplayer.source) return
        if(mediaplayer.playbackState === MediaPlayer.PlayingState)
        {
            mediaplayer.pause()
            //playingState = 0
        }
        else if(mediaplayer.playbackState === MediaPlayer.PausedState)
        {
            mediaplayer.play()
            //playingState = 1
        }
    }

    function playNext(type = "natural")
    {
        if(playList.length<1) return
        switch(currentPlayMode)
        {

        case 0:
        {
            if(type==="natural")
            {
                mediaplayer.play()
                break
            }
        }
        case 1:
        {
            current = (current+1)%playList.length
            break
        }
        case 2:
        {
            var random = parseInt(Math.random()*playList.length)
            current = random===current?random+1:random
            break
        }

        //current = (current+1)%playList.length
        }
    }

    function changePlayMode()
    {
        currentPlayMode = (currentPlayMode+1)%playModeList.length
        settings.setValue("currentPlayMode",currentPlayMode)
    }

    function playMusic()
    {
        if(current<0) return
        if(playList.length<current + 1) return
        if(playList[current].type==="1")
        {
            getLocalMusic()
        }
        else
        {
            getWebMusic()
        }
        saveHistory(current)
    }

    function getLocalMusic()
    {
        var currentItem = playList[current]
        mediaplayer.source = currentItem.url
        mediaplayer.play()
        musicName = currentItem.name
        musicArtist = currentItem.artist
        musicCover="qrc:/images/player"
        pageDetailView.lyricsList = ["暂无歌词"]

    }

    function getWebMusic()
    {
        loading.open()
        var id = playList[current].id
        if(!id) return

        musicName = playList[current].name
        musicArtist = playList[current].artist

        function onReply(reply)
        {
            loading.close()
            http.onReplySignal.disconnect(onReply)

            try
            {
                if(reply.length<1)
                {
                    notification.openError("请求歌曲链接为空！")
                    return
                }

                var data = JSON.parse(reply).data[0]
                var url = data.url
                var time = data.time

                setSlider(0, time, 0)

                if(!url) return

                var cover = playList[current].cover
                // console.log("playList[current]:"+playList[current].cover)
                // console.log("cover:"+cover)
                // console.log("cover.length:"+cover.length)
                //getCover(id)
                if(cover.length<1)
                {
                    getCover(id)
                }
                else
                {
                    musicCover = cover
                    getLyric(id)

                }

                mediaplayer.source = url
                mediaplayer.play()
                playbackChangeCallbackEnabled = true
                //console.log("mediaplayer...")
            }
            catch(err)
            {
                notification.openError("请求歌曲链接出错")
            }

        }

        http.onReplySignal.connect(onReply)
        //console.log("song/url?id="+id)
        http.connet("song/url?id="+id)
    }

    function setSlider(from=0, to=100, value=0)
    {
        sliderFrom = from
        sliderTo=to
        sliderValue = value

        var va_mm= parseInt(value/1000/60) +""
        va_mm = va_mm.length<2?"0"+va_mm:va_mm
        var va_ss = parseInt(value/1000%60) +""
        va_ss = va_ss.length<2?"0"+va_ss:va_ss

        var to_mm= parseInt(to/1000/60) +""
        to_mm = to_mm.length<2?"0"+to_mm:to_mm
        var to_ss = parseInt(to/1000%60) +""
        to_ss = to_ss.length<2?"0"+to_ss:to_ss

        timeText.text = va_mm+":"+va_ss+"/"+to_mm+":"+to_ss
    }

    function getCover(id)
    {
        loading.open()
        function onReply(reply)
        {
            loading.close()
            http.onReplySignal.disconnect(onReply)

            getLyric(id)

            try
            {
                if(reply.length<1)
                {
                    notification.openError("请求歌曲图片为空！")
                    return
                }
                //console.log("图片:",id)
                var song = JSON.parse(reply).songs[0]
                musicCover=song.al.picUrl

                if(musicName.length<1) musicName = song.name
                if(musicArtist.length<1) musicArtist = song.ar[0].name
            }
            catch(err)
            {
                notification.openError("请求歌曲歌曲图片出错！")
            }
        }
        http.onReplySignal.connect(onReply)
        http.connet("song/detail?ids="+id)
    }

    function getLyric(id)
    {
        loading.open()
        function onReply(reply)
        {
            loading.close()
            http.onReplySignal.disconnect(onReply)

            try
            {
                if(reply.length<1)
                {
                    notification.openError("请求歌曲歌词为空！")
                    return
                }
                //console.log("歌词：",id)
                var lyric = JSON.parse(reply).lrc.lyric

                //console.log(lyric)
                if(lyric.length<1) return
                var lyrics = (lyric.replace(/\[.*\]/gi,"")).split("\n")

                if(lyrics.length>0)
                {
                    pageDetailView.lyricsList=lyrics
                }

                var times = []
                lyric.replace(/\[.*\]/gi, function(match, index)
                {
                    if(match.length>2)
                    {
                        var time = match.substr(1,match.length-2)
                        var arr= time.split(":")
                        var timeValue = arr.length>0?parseInt(arr[0])*60*1000:0
                        arr = arr.length>1?arr[1].split('.'):[0,0]
                        timeValue += arr.length>0?parseInt(arr[0])*1000:0
                        timeValue += arr.length>1?parseInt(arr[1])*10:0
                        times.push(timeValue)
                    }
                }
                )
                mediaplayer.times = times
            }
            catch(err)
            {
                //console.log(err)
                notification.openError("请求歌曲歌词出错！")
            }

        }
        http.onReplySignal.connect(onReply)
        http.connet("lyric?id="+id)
    }
}
